from django.shortcuts import render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


from .models import question, answer
from .forms import questionForm, answerForm


def main(request):
    questions = question.objects.all().order_by('id').reverse()

    return render(request,'qna/index.html', {'question': questions})

def question_detail(request, question_id):
    questions  = question.objects.get(id=question_id)
    answers = answer.objects.all().filter(question=question_id)

    #answers  = answer.objects.filter(question=question_id)
    return render(request, 'qna/detail.html', {'question': questions, 'answer':answers})

def index(request):
    questions = question.objects.all().order_by('id').reverse()
    paginator = Paginator(questions, 9)
    page = request.GET.get('page')
    page_obj = paginator.get_page(page)
    try:
        questions = paginator.page(page)
    except PageNotAnInteger:
        questions = paginator.page(1)
    except EmptyPage:
        questions = paginator.page(paginator.num_pages)
    return render(request, 'qna/index.html', {'question': questions.object_list, 'page_obj': page_obj})

def question_new(request):
    if request.method == 'POST':
        qForm = questionForm(request.POST)
        if qForm.is_valid():
            quest = qForm.save(commit=False)
            quest.name  = request.user
            quest.save()
            return redirect('/')
    else:
        qForm  = questionForm()
    return render(request,  'qna/q_new.html',  {'form': qForm})

def answer_new(request, question_id):
    questions  = question.objects.get(id=question_id)
    if request.method  ==  'POST':
        aForm = answerForm(request.POST)
        if aForm.is_valid():
            ans = aForm.save(commit=False)
            ans.name = request.user
            ans.question_id = question_id
            ans.save()

            return redirect('/detail/'+str(questions.id))
    else:
        aForm = answerForm()
    return render(request, 'qna/a_new.html', {'form': aForm, 'question': questions})

def registration(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            # получаем имя пользователя и пароль из формы
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            # выполняем аутентификацию
            user = authenticate(username=username, password=password, is_staff=True)
            user.groups.is_staff= True
            login(request, user)
            return redirect('/')
    else:
        form = UserCreationForm()
    return render(request, 'registration/signup.html', {'form': form})
